const { Table, Input, Popconfirm,Button,message } = antd;

const data = [];
for (let i = 0; i < 3; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
  });
}

const EditableCell = ({ editable, value, onChange }) => (
  <div>
    {editable
      ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)} />
      : value
    }
  </div>
);

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       selectedRowKeys: [], // Check here to configure the default column
       loading: false,
       data:data,
       count:3,
       deleting:false,
    };
    this.columns = [{
      title: 'name',
      dataIndex: 'name',
      width: '20%',
      render: (text, record) => this.renderColumns(text, record, 'name'),
    }, {
      title: 'age',
      dataIndex: 'age',
      width: '15%',
      render: (text, record) => this.renderColumns(text, record, 'age'),
    }, {
      title: 'address',
      dataIndex: 'address',
      width: '40%',
      render: (text, record) => this.renderColumns(text, record, 'address'),
    }, {
      title: 'operation',
      dataIndex: 'operation',
      render: (text, record) => {
        const { editable } = record;
        return (
          <div className="editable-row-operations">
            {
              editable ?
                <span>
                  <a onClick={() => this.save(record.key)}>Save</a>
                  <Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.key)}>
                    <a>Cancel</a>
                  </Popconfirm>
                </span>
                : <a onClick={() => this.edit(record.key)}>Edit</a>
            }
            {
              this.state.data.length > 0 && !editable ?
              (
                <Popconfirm title="Sure to delete?" onConfirm={() => this.onDelete(record.key)}>
                  <a href="#">Delete</a>
                </Popconfirm>
              ) 
                : null
            }
          </div>
        );
      },
    }];
    this.cacheData = data.map(item => ({ ...item }));
  }
  renderColumns(text, record, column) {
    return (
      <EditableCell
        editable={record.editable}
        value={text}
        onChange={value => this.handleChange(value, record.key, column)}
      />
    );
  }
  handleChange(value, key, column) {
    const newData = [...this.state.data];
    const target = newData.filter(item => key === item.key)[0];
    if (target) {
      target[column] = value;
      this.setState({ data: newData });
    }
  }
  edit(key) {
    const newData = [...this.state.data];
    const target = newData.filter(item => key === item.key)[0];
    if (target) {
      target.editable = true;
      this.setState({ data: newData });
    }
  }
  save(key) {
    const newData = [...this.state.data];
    const target = newData.filter(item => key === item.key)[0];
    if (target) {
      delete target.editable;
      this.setState({ data: newData });
      this.cacheData = newData.map(item => ({ ...item }));
    }
  }
  cancel(key) {
    const newData = [...this.state.data];
    const target = newData.filter(item => key === item.key)[0];
    if (target) {
      Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
      delete target.editable;
      this.setState({ data: newData });
    }
  }
  onDelete = (key) => {
    const data = [...this.state.data];
    this.setState({ data: data.filter(item => item.key !== key), selectedRowKeys:[]});
    this.deleting();
  }
  isInArray = (value) =>{
    for(var i = 0; i < this.state.selectedRowKeys.length; i++){
        if(value === this.state.selectedRowKeys[i]){
            return true;
        }
    }
    return false;
  }
  onBatchDelete = () => {
    const data = [...this.state.data];
    this.setState({ data: data.filter(item => !this.isInArray(item.key))});
    this.deleting();
  }
  deleting=()=>{
    this.setState({ deleting: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        deleting: false,
      });
      message.info('记录删除成功');
    }, 1000);
  }
  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
      message.info('记录重新加载成功');
    }, 1000);
  }
  onSelectChange = (selectedRowKeys,selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    this.setState({ selectedRowKeys });
  }
  handleAdd = () => {
    const { count, data } = this.state;
    const newData = {
      key: count,
      name: `Edrward King ${count}`,
      age: 32,
      address: `London, Park Lane no. ${count}`,
    };
    this.setState({
      data: [...data, newData],
      count: count + 1,
    });
  }
  render() {
    const { loading, selectedRowKeys,deleting } = this.state;
    const hasSelected = selectedRowKeys.length > 0;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
         disabled: record.name === 'Edrward 3', // Column configuration not to be checked
         name: record.name,
      }),
      selections: [{
        key: 'all-data',
        text: 'Select All Data',
        onSelect: () => {
          const data = [...this.state.data];
          const result=[];
          data.forEach(item=>{
              result.push(item.key);
          })
          this.setState({
            selectedRowKeys:result
          });
        },
      }]
    };
    return (
       <div>
         <div style={{ marginBottom: 16 }}>
            <Button
               type="primary"
               onClick={this.start}
               disabled={!hasSelected}
               loading={loading}
            >
               Reload
            </Button>
            <Button style={{margin:5}} className="editable-add-btn" onClick={this.handleAdd}>Add</Button>
            <Button
               type="primary"
               onClick={this.onBatchDelete}
               disabled={!hasSelected}
               loading={deleting}
            >
               Delete
            </Button>
            <Button style={{margin:5}}
               type="primary"
               onClick={this.start}
               disabled={!hasSelected}
            >
               Alter
            </Button>
            <span style={{ marginLeft: 8 }}>
            </span>
         </div>
         <Table bordered rowSelection={rowSelection} dataSource={this.state.data} columns={this.columns} />
       </div>
    )
  }
}

ReactDOM.render(<EditableTable />, mountNode);